import { Button, message, Popconfirm, Typography } from "antd";
import Table, { ColumnProps } from "antd/lib/table";
import {
	forwardRef,
	ForwardRefRenderFunction,
	useContext,
	useEffect,
	useImperativeHandle,
	useMemo,
	useRef,
	useState,
} from "react";
import {
	accreditPermission,
	deleteSource,
	getUnAccreditedPermissions,
} from "src/api";
import EllipsisText from "@/components/dataPresentation/EllipsisText";
import { AdminContext } from "src/layout/admin/admin";
import { RoleContext } from "../Role";
import { Permission, PermissionRecord } from "../RoleType";

interface UnAuthPermissionTableProps {
	fetchPromissions: () => Promise<unknown>;
	visible: boolean;
	handleEditPermission: (record: PermissionRecord) => void;
}
export interface UnAuthPermissionTableRef {
	fetchUnAuthPermissions: () => Promise<unknown>;
}
const UnAuthPermissionTable: ForwardRefRenderFunction<
	UnAuthPermissionTableRef,
	UnAuthPermissionTableProps
> = ({ fetchPromissions, visible, handleEditPermission }, ref) => {
	useImperativeHandle(ref, () => ({
		fetchUnAuthPermissions,
	}));
	const pageRef = useRef(1);
	const pageSizeRef = useRef(10);
	const [pageOptions, setPageOptions] = useState({
		current: pageRef.current,
		pageSize: pageSizeRef.current,
		total: 0,
	});
	const { operatedRole } = useContext(RoleContext);
	const { fetchMenu, fetchMenuAndRoutes } = useContext(AdminContext);
	const columns = useMemo<ColumnProps<PermissionRecord>[]>(
		() => [
			{
				title: "权限名",
				dataIndex: "name",
				width: "220px",
				render(name) {
					return <EllipsisText>{name}</EllipsisText>;
				},
			},
			{
				title: "权限类型",
				width: "100px",
				dataIndex: "type",
				render(type: PermissionRecord["type"]) {
					return type === Permission.interface ? (
						<Typography.Text type="success">
							接口权限
						</Typography.Text>
					) : type === Permission.menu ? (
						<Typography.Text keyboard>菜单</Typography.Text>
					) : type === Permission.route ? (
						<Typography.Text keyboard>页面路由</Typography.Text>
					) : (
						"未知"
					);
				},
			},
			{
				title: "图标",
				dataIndex: "icon",
				width: "60px",
				render(icon: string) {
					// eslint-disable-next-line @typescript-eslint/no-var-requires
					const Icon = require("@ant-design/icons")[icon];
					if (!Icon) return "";
					return (
						<div className="text-center">
							<Icon />
						</div>
					);
				},
			},
			{
				title: "权限地址",
				dataIndex: "url",
				width: "250px",
				render(name) {
					return <EllipsisText>{name}</EllipsisText>;
				},
			},
			{
				title: "请求方法",
				dataIndex: "method",
				width: "100px",
			},
			{
				title: "父菜单",
				dataIndex: "parentName",
				width: "120px",
				render(parentName) {
					return <EllipsisText>{parentName}</EllipsisText>;
				},
			},
			{
				title: "操作",
				render(_, record) {
					return (
						<>
							<Button
								size="small"
								type="primary"
								onClick={() => {
									if (!operatedRole.current?._id)
										return message.error("数据id不存在");
									accreditPermission({
										role_id: operatedRole.current._id,
										permission_id: record._id,
									}).then(async () => {
										await fetchUnAuthPermissions();
										await fetchPromissions();
										if (record.type === 2) {
											fetchMenu();
											fetchMenuAndRoutes();
										}
										message.success("已授权");
									});
								}}
							>
								授权
							</Button>
							<Button
								size="small"
								className="ml-2"
								onClick={() => handleEditPermission(record)}
							>
								编辑
							</Button>
							<Popconfirm
								onConfirm={async () => {
									await deleteSource({
										source: "permission",
										id: record._id,
									});
									await fetchUnAuthPermissions();
									// if (record.type === 2) fetchMenu();
									message.success("删除成功");
								}}
								className="ml-2"
								title={`确定删除【${record.name}】吗？`}
							>
								<Button size="small" danger>
									删除
								</Button>
							</Popconfirm>
						</>
					);
				},
			},
		],
		[]
	);
	const [unAuthPermissionList, setUnAuthPermissionList] = useState<
		PermissionRecord[]
	>([]);
	const fetchUnAuthPermissions = async () => {
		const roleId = operatedRole.current?._id;
		if (!roleId) return message.error("角色id不存在");
		const res = await getUnAccreditedPermissions({
			page: pageRef.current,
			pageSize: pageSizeRef.current,
			roleId,
		});
		setUnAuthPermissionList(res.data?.data || []);
		setPageOptions({
			current: pageRef.current,
			pageSize: pageSizeRef.current,
			total: Number(res.data?.total) || 0,
		});
		return;
	};
	useEffect(() => {
		if (visible) {
			fetchUnAuthPermissions();
		}
	}, [visible]);
	return (
		<Table
			title={() => (
				<h1 className="text-lg text-center">
					<span className="font-bold">
						【{operatedRole.current?.name}】
					</span>
					未拥有的权限
				</h1>
			)}
			columns={columns}
			locale={{ emptyText: "所有权限都有咯~" }}
			dataSource={unAuthPermissionList.map((item, key) => ({
				...item,
				key,
			}))}
			pagination={{
				...pageOptions,
				onChange(page, pageSize) {
					pageRef.current = page;
					pageSizeRef.current = pageSize;
					setPageOptions({
						...pageOptions,
						current: pageRef.current,
						pageSize: pageSizeRef.current,
					});
					fetchUnAuthPermissions();
				},
			}}
		/>
	);
};

export default forwardRef(UnAuthPermissionTable);
